package com.code.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    public JDBCUtils() {
    }

    private static String url = null;
    private static String usr = null;
    private static String pwd = null;

    static {

        try {
            Properties prop = new Properties();
            // 读取配置文件
            InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
            prop.load(in);

            //解析
            Class.forName(prop.getProperty("driver"));
            url = prop.getProperty("url");
            usr = prop.getProperty("usr");
            pwd = prop.getProperty("pwd");


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {

        Connection  conn = null;

        try {
             conn = DriverManager.getConnection(url, usr, pwd);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return conn;

    }

    public static void closeConnection(Connection conn, Statement stmt, ResultSet rs) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

}
